<script setup>
import Card from "@/componments/Card.vue";
import { Message, Notebook, Select, User } from "@element-plus/icons-vue";
import { useStore } from 'vuex';
import {computed, reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import {accessHeader, get, post} from "@/net/index.js";
import axios from "axios";

const store = useStore();
const des = ref("");
const user = computed(() => store.state.user);
const registerTime = computed(() => new Date(store.state.user.date).toLocaleString());
const baseForm = reactive({
  username: '',
  gender: 1,
  phone: '',
  qq: '',
  vx: '',
  des: '',
});

const emailForm = reactive({
  email: '',
  code: '',
});

// 表单验证规则
const baseRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
    { min: 2, max: 20, message: '用户名长度应在 2 到 10 个字符之间', trigger: ['blur', 'change'] },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: ['blur', 'change'] },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: ['blur', 'change'] },
  ],
  qq: [
    { pattern: /^[1-9][0-9]{4,10}$/, message: '请输入有效的QQ号', trigger: ['blur', 'change'] },
  ],
  vx: [
    { pattern: /^[a-zA-Z][a-zA-Z\d_-]{5,19}$/, message: '请输入有效的微信号', trigger: ['blur', 'change'] },
  ],
};

const emailRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: ['blur', 'change'] },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] },
  ],
  code: [
    { required: true, message: '请输入邮箱验证码', trigger: ['blur', 'change'] },
    { min: 6, max: 6, message: '验证码长度应为 6 个字符', trigger: ['blur', 'change'] },
  ],
};

// 表单实例
const baseFormRef = ref();
const emailFormRef = ref();
get("api/user/details", data => {
  baseForm.username = store.state.user.username;
  baseForm.gender = data.gender;
  baseForm.phone = data.phone;
  baseForm.qq = data.qq;
  baseForm.vx = data.vx;
  baseForm.des = data.des;
  emailForm.email = store.state.user.email;
  des.value = data.des;
})

// 保存用户信息
const saveUserInfo = () => {
  baseFormRef.value.validate((valid) => {
    if (valid) {
      post("api/user/save_details",baseForm, () =>{
        ElMessage.success("用户信息保存成功")
        store.dispatch('fetchUser')
        des.value = baseForm.des;
      })

    } else {
    ElMessage.warning("请填写完整信息");
      return false;
    }
  });
};
const ask_code = () => {
  get(`api/auth/ask_code?type=Modify&email=${emailForm.email}`, () =>{
    ElMessage.success(`验证码已发送至${emailForm.email}的邮箱，请注意查收`)
  })
}
function  beforeAvatarUpload(rawFile){
  if(rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' ){
    ElMessage.error("请上传jpg或png格式的图片")
    return false;
  }
  else if(rawFile.size > 1024*100){
    ElMessage.error("图片大小不能超过100KB")
    return false;
  }
  return true;
}
function uploadSuccess(response){
  ElMessage.success("头像更改成功")
  store.state.user.avatar = response.data;

}

// 更新电子邮件
const updateEmail = () => {
  emailFormRef.value.validate((valid) => {
    if (valid) {
      // 处理更新逻辑
      post("api/user/reset_email",emailForm, () =>{
        ElMessage.success("更新邮箱成功")
      })

    } else {
      ElMessage.warning("请正确填写邮箱和验证码")
      return false;
    }
  });
};
</script>

<template>
  <div style="display: flex;max-width: 950px;margin: auto" >
    <div class="setting-left">
      <card :icon="User" title="用户信息" desc="修改用户信息">
        <el-form ref="baseFormRef" :model="baseForm" :rules="baseRules" label-position="top" style="margin:0 10px 10px 10px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="baseForm.username" maxlength="10"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="baseForm.gender">
              <el-radio :label="0">男</el-radio>
              <el-radio :label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="baseForm.phone" maxlength="11"></el-input>
          </el-form-item>
          <el-form-item label="QQ号" prop="qq">
            <el-input v-model="baseForm.qq" maxlength="13"></el-input>
          </el-form-item>
          <el-form-item label="微信号" prop="vx">
            <el-input v-model="baseForm.vx" maxlength="20"></el-input>
          </el-form-item>
          <el-form-item label="个人简介" prop="des">
            <el-input v-model="baseForm.des" type="textarea" :rows="5" maxlength="200"></el-input>
          </el-form-item>
          <div>
            <el-button :icon="Select" type="primary" style="width: 100%" @click="saveUserInfo">保存用户信息</el-button>
          </div>
        </el-form>
      </card>
      <card style="margin-top: 10px" :icon="Message" title="电子邮件设置" desc="管理电子邮件">
        <el-form ref="emailFormRef" :model="emailForm" :rules="emailRules" label-position="top" style="margin:0 10px 10px 10px">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="emailForm.email"></el-input>
          </el-form-item>
          <el-form-item label="邮箱验证码" prop="code">
            <el-row style="width: 100%" :gutter="10">
              <el-col :span="18">
                <el-input v-model="emailForm.code"></el-input>
              </el-col>
              <el-col :span="6">
                <el-button type="primary" plain style="width: 100%" @click="ask_code">发送验证码</el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <div>
            <el-button :icon="Select" type="primary" style="width: 100%" @click="updateEmail">更新绑定邮箱</el-button>
          </div>
        </el-form>
      </card>
    </div>
    <div class="setting-right">
      <div style="position: sticky; top: 20px">
        <card>
          <div style="text-align: center; padding: 5px 15px 0px 15px">
            <div>
              <el-avatar size="120" :src="store.getters.avatarGet">
              </el-avatar>
              <div style="margin-top: 5px">
                <el-upload
                :action="axios.defaults.baseURL + '/api/image/avatar'
                 " :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-success="uploadSuccess"
                :headers="accessHeader()"
                >
                  <el-button round size="small">修改头像</el-button>
                </el-upload>
              </div>

              <div style="font-weight: bold">
                你好, {{ user.username }}
              </div>
              <el-divider style="margin: 10px 0"></el-divider>
              <div style="font-size: 14px; color: gray">
                  {{des || "这个用户很懒，没有填写个人简介"}}
              </div>
            </div>
          </div>
        </card>
        <card style="margin-top: 10px">
          <div>
            <div style="font-size: 16px; margin: 10px 0">
              账号注册时间：{{ registerTime }}
            </div>
            <div style="font-size: 14px; color: gray">
              欢迎加入我们的学习论坛...
            </div>
          </div>
        </card>
      </div>
    </div>
  </div>
</template>

<style scoped>
.setting-left {
  flex: 1;
  margin: 20px;
}
.setting-right {
  width: 300px;
  margin: 20px 0 20px 0px;
}
</style>
